package com.valuegroup.smarttodo.ui.programme.ideality;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.model.AppStatus;
import com.valuegroup.smarttodo.data.model.Ideality;
import com.valuegroup.smarttodo.data.model.Remark;
import com.valuegroup.smarttodo.plugins.icaruseditor.Icarus;
import com.valuegroup.smarttodo.plugins.icaruseditor.TextViewToolbar;
import com.valuegroup.smarttodo.plugins.icaruseditor.entity.Options;
import com.valuegroup.smarttodo.plugins.imgsel.ISNav;
import com.valuegroup.smarttodo.plugins.imgsel.config.ISListConfig;
import com.valuegroup.smarttodo.plugins.imgsel.ui.ISListActivity;
import com.valuegroup.smarttodo.ui.BaseActivity;
import com.valuegroup.smarttodo.util.AlertUtils;
import com.valuegroup.smarttodo.util.CollectionUtils;

import java.io.File;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 理想详情
 */
public class IdealityActivity extends BaseActivity {

    @BindView(R.id.btnBack)
    ImageButton btnBack;
    @BindView(R.id.labTitle)
    TextView labTitle;
    @BindView(R.id.btnFinish)
    TextView btnFinish;
    @BindView(R.id.imgCover)
    ImageView imgCover;
    @BindView(R.id.layoutImgCover)
    LinearLayout layoutImgCover;
    @BindView(R.id.btnSetCover)
    LinearLayout btnSetCover;
    @BindView(R.id.editor)
    WebView editor;

    private Long DATA_ID;
    private Integer DATA_POSITION;
    private Ideality DATA;
    private Remark DATA_REMARK;
    private boolean doDel = false;

    private Icarus icarus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ideality);
        ButterKnife.bind(this);

        DATA_ID = getIntent().getLongExtra(PARAMS_KEY, 0);
        DATA_POSITION = getIntent().getIntExtra(PARAMS_POSITION, 0);
        DATA = ServiceFactory.getInstance().getIdealityService().getIdealityDao().load(DATA_ID);
        DATA_REMARK = ServiceFactory.getInstance().getRemarkService().getRemark(AppStatus.RemarkType.IDEALITY, DATA_ID);

        if (DATA_ID != 0 && DATA == null) {
            AlertUtils.showToast(this, R.string.not_found_record);
            finish();
            return;
        }

        if (DATA_ID == 0) {
            DATA = ServiceFactory.getInstance().getIdealityService().getDefaultIdeality();
            DATA.setTitle("");
            DATA.setShortTitle("");
        }

        initView();
        initData();
    }

    private void initData() {
        labTitle.setText(DATA.getTitle());

        if (DATA.getIsFinish()) {
            btnFinish.setText(getResources().getString(R.string.do_un_finish));
        }

        if (DATA_REMARK != null && !TextUtils.isEmpty(DATA_REMARK.getContent())) {
            icarus.setContent(DATA_REMARK.getContent());
        }
    }

    private void initView() {

        // 设置封面图片
        if (!TextUtils.isEmpty(DATA.getCoverPath())) {
            //Uri u = new Uri.Builder().scheme("file").path("//" + DATA.getImagePath()).build();
            //imgCover.setImageURI(u);
            btnSetCover.setVisibility(View.GONE);
            layoutImgCover.setVisibility(View.VISIBLE);

            // 设置圆角图片
            // RoundedBitmapDrawable roundedBitmapDrawable1 = RoundedBitmapDrawableFactory.create(getResources(), BitmapFactory.decodeResource(getResources(), R.drawable.ideality_piano));
            /*RoundedBitmapDrawable roundedBitmapDrawable1 = RoundedBitmapDrawableFactory.create(getResources(), DATA.getCoverPath());
            roundedBitmapDrawable1.setCornerRadius(6);
            imgCover.setImageDrawable(roundedBitmapDrawable1);*/

            RequestOptions options = RequestOptions
                    .bitmapTransform(new RoundedCorners(6)) //设置图片圆角角度
                    .diskCacheStrategy(DiskCacheStrategy.NONE)//不做磁盘缓存
                    .skipMemoryCache(true)//不做内存缓存
                    .placeholder(R.drawable.ic_default_image)//图片加载出来前，显示的图片
                    .fallback(R.drawable.ic_default_image) //url为空的时候,显示的图片
                    .error(R.drawable.ic_default_image);//图片加载失败后，显示的图片

            Uri u = new Uri.Builder().scheme("file").path("//" + DATA.getCoverPath()).build();
            Glide.with(this).load(u)
                    .apply(options)
                    .into(imgCover);
        } else {
            btnSetCover.setVisibility(View.VISIBLE);
            layoutImgCover.setVisibility(View.GONE);
        }

        TextViewToolbar toolbar = new TextViewToolbar();
        Options options = new Options();
        options.setPlaceholder("描述你的理想...");
        //  img: ['src', 'alt', 'width', 'height', 'data-non-image']
        // a: ['href', 'target']
        options.addAllowedAttributes("img", Arrays.asList("data-type", "data-id", "class", "src", "alt", "width", "height", "data-non-image"));
        options.addAllowedAttributes("iframe", Arrays.asList("data-type", "data-id", "class", "src", "width", "height"));
        options.addAllowedAttributes("a", Arrays.asList("data-type", "data-id", "class", "href", "target", "title"));

        icarus = new Icarus(toolbar, options, editor);
        icarus.loadCSS("file:///android_asset/editor.css");
        // icarus.loadJs("file:///android_asset/test.js");
        icarus.render();

    }

    private static final int REQ_CAMERA_PERMISSION = 59;
    protected static final int REQ_SELECT_IMAGE = 879;

    @OnClick({R.id.btnBack, R.id.btnFinish, R.id.imgCover, R.id.layoutImgCover, R.id.btnSetCover})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnBack:
                finishAfterTransition();
                break;
            case R.id.btnFinish:
                Ideality temp = ServiceFactory.getInstance().getIdealityService().doFinish(DATA_ID);
                if (temp != null) {
                    DATA.setIsFinish(temp.getIsFinish());
                    DATA.setFinishDt(temp.getFinishDt());
                    if (temp.getIsFinish()) {
                        //btnFinish.setText(getResources().getString(R.string.do_un_finish));
                        finishAfterTransition();
                    }
                }
                break;
//            case R.id.layoutMain:
//                Intent intent = new Intent(this, IdealityDetailMainActivity.class);
//                intent.putExtra(IdealityDetailMainActivity.PARAMS_KEY, DATA_ID);
//                startActivityForResult(intent, 1004);
//                break;
            case R.id.imgCover:
            case R.id.btnSetCover:
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{Manifest.permission.CAMERA},
                            REQ_CAMERA_PERMISSION);
                    return;
                }

                openImageSelector(true);
                break;
            /*case R.id.btnDel:

                AlertUtils.delOrderDialog(view.getContext(),
                        String.format(getResources().getString(R.string.alt_del), DATA.getTitle()),
                        (dialog, which) -> {

                            if (DATA != null && !TextUtils.isEmpty(DATA.getCoverPath())) {
                                // 删除已有文件
                                File rootDir = new File(DATA.getCoverPath());
                                if (rootDir.exists()) {
                                    rootDir.delete();
                                }
                            }

                            ServiceFactory.getInstance().getIdealityService().delIdeality(DATA.getId());

                            // 跳转至习惯列表
                            doDel = true;
                            setCloseParams();
                            finishAfterTransition();
                        });
                break;*/
        }
    }

    private void setCloseParams() {
        Intent intent = new Intent();
        intent.putExtra(PARAMS_POSITION, DATA_POSITION);
        intent.putExtra(PARAMS_KEY, DATA_ID);
        intent.putExtra(DEL_TAG, doDel);
        setResult(RESULT_OK, intent);
    }

    private void openImageSelector(boolean supportSelfie) {
        ISListConfig config = new ISListConfig.Builder()
                // 是否多选, 默认true
                .multiSelect(false)
                // 是否记住上次选中记录, 仅当multiSelect为true的时候配置，默认为true
                .rememberSelected(false)
                // “确定”按钮背景色
                .btnBgColor(Color.GRAY)
                // “确定”按钮文字颜色
                .btnTextColor(Color.BLUE)
                // 使用沉浸式状态栏
                .statusBarColor(Color.parseColor("#3F51B5"))
                // 返回图标ResId
                .backResId(R.drawable.ic_back)
                // 标题
                //.title(getString(R.string.webview_select_picture))
                .title("选择图片")
                // 标题文字颜色
                .titleColor(Color.WHITE)
                // TitleBar背景色
                .titleBgColor(Color.parseColor("#3F51B5"))
                .needCrop(false)
                .cropSize(16, 9, 90, 160)
                // 第一个是否显示相机，默认true
                .needCamera(supportSelfie)
                // 最大选择图片数量，默认9
                .maxNum(9)
                .build();
        // 跳转到图片选择器
        ISNav.getInstance().toListActivity(this, config, REQ_SELECT_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 图片选择结果回调
        if (requestCode == REQ_SELECT_IMAGE
                && resultCode == Activity.RESULT_OK
                && data != null) {
            List<String> pathList = data.getStringArrayListExtra(ISListActivity.INTENT_RESULT);
            if (CollectionUtils.isNotEmpty(pathList)) {
                String path = pathList.get(0);
                System.out.println("path" + path);
                //create ImageObject
                // Uri imageUri = mListener.createImage(path);
                //insert to note
                // mEditor.insertImage("untitled", imageUri.toString());

                Uri u = new Uri.Builder().scheme("file").path("//" + path).build();
                //System.out.println(">>>>>>>>>>>>>>>>>>>>>> paramsString:" + u.toString());

                // 创建根目录
                File rootDir = new File(Environment.getExternalStorageDirectory(), "SmartTodo" + File.separator + "img" + File.separator + "ideality");
                if (!rootDir.exists()) {
                    rootDir.mkdirs();
                }

                // 指定输出文件
                File cropImageFile = new File(rootDir, System.currentTimeMillis() + ".jpg");
                //File cropImageFile = new File(FileUtils.createRootPath(this) + "/" + System.currentTimeMillis() + ".jpg");

                // 图片裁剪
                CropImage.activity(u)
                        .setGuidelines(CropImageView.Guidelines.ON)
                        .setActivityTitle("图片裁剪")
                        .setCropShape(CropImageView.CropShape.RECTANGLE)
                        .setCropMenuCropButtonTitle("Done")
                        .setOutputUri(Uri.fromFile(cropImageFile))
                        .start(this);

            }
        } else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {
                //System.out.println(">>>>>>>>>>>>>>>>" + result.getUri().getPath());

                btnSetCover.setVisibility(View.GONE);
                imgCover.setImageURI(result.getUri());
                layoutImgCover.setVisibility(View.VISIBLE);

                if (DATA != null && !TextUtils.isEmpty(DATA.getCoverPath())) {
                    // 删除已有文件
                    File rootDir = new File(DATA.getCoverPath());
                    if (rootDir.exists()) {
                        rootDir.delete();
                    }
                }
                // 保存新的文件信息
                DATA.setCoverPath(result.getUri().getPath());
                if (DATA_ID != 0) {
                    ServiceFactory.getInstance().getIdealityService().saveImgCover(DATA_ID, result.getUri().getPath());
                }

            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        editor.destroy();
    }
}
